package com.zxmr.action;

import java.io.IOException;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.rabbitmq.client.Channel;
import com.zxmr.fastjson.filter.RequestOnlyIDSerializeFilter;
import com.zxmr.rabbit.ChannelFactory;

public class Response {

	Request request;
	
	/*
	 *  this result code only indicate the request is successfully handled or not, 
	 *  it does not care about the logic level result code
	 */
	ResultCode result;
	ResponsePayload payload;
	
	public Request getRequest() {
		return request;
	}
	public void setRequest(Request request) {
		this.request = request;
	}
	public ResponsePayload getPayload() {
		return payload;
	}
	public void setPayload(ResponsePayload payload) {
		this.payload = payload;
	}
	
	public boolean send() throws IOException
	{
		// get one channel
		Channel channel = ChannelFactory.createChannel();
		if(channel == null)
		{
			return false;
		}

		byte[] data = this.encode();
	
		channel.basicPublish("", request.getRequestProperties().getReplyTo(), null, data);
		channel.close();
		return true;
	}
	private byte[] encode()
	{
		SerializeWriter sw = new SerializeWriter();
		JSONSerializer serializer = new JSONSerializer(sw);
		serializer.getPropertyFilters().add(new RequestOnlyIDSerializeFilter());
		
		serializer.write(this);
		
		System.out.println(sw.toString());
		return sw.toBytes("UTF-8");
	}
	public ResultCode getResult() {
		return result;
	}
	public void setResult(ResultCode result) {
		this.result = result;
	}
	
}
